package lg.minecraft.plugin.testeconomy.config;

import lombok.Getter;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.IOException;

@Getter
public class BaseConfig extends YamlConfiguration {

    protected final JavaPlugin plugin;
    protected final File file;
    protected final File absoluteFile;

    public BaseConfig(JavaPlugin plugin, String fileName) {
        this.plugin = plugin;
        this.file = new File(plugin.getDataFolder(), fileName);
        this.absoluteFile = file.getAbsoluteFile();
    }

    public void load() {
        if (absoluteFile.exists()) {
            try {
                this.load(absoluteFile);
            } catch (Exception e) {
                plugin.getLogger().severe("无法加载配置文件: " + absoluteFile.getPath());
            }
        }
    }

    public void save() {
        if (!absoluteFile.exists()) {
            this.createDirectory();
        }
        try {
            this.save(absoluteFile);
        } catch (IOException e) {
            plugin.getLogger().severe("无法保存配置文件: " + absoluteFile.getPath());
        }
    }

    public void saveDefault() {
        saveDefault(false);
    }

    public void saveDefault(boolean replace) {
        saveDefault("", replace);
    }

    public void saveDefault(String resourcePath, boolean replace) {
        if (!absoluteFile.exists() || replace) {
            plugin.saveResource(resourcePath + file.getName(), replace);
        }
    }

    public void createDirectory() {
        File directory = this.absoluteFile.getParentFile();
        if (!directory.exists() && !directory.mkdirs()) {
            plugin.getLogger().severe("无法创建目录: " + directory.getPath());
        }
    }

}